package main

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

const (
	DSN             = "root:changyz...@(42.192.221.26:3306)/gin_class?charset=utf8mb4&parseTime=True&loc=Local"
	CreateBatchSize = 1000
)

// 格式化
func main() {
	initDBStudent()
	//initDBPerson()
	//linkCreate()
	//selectExec()
	//
	//updateExec()
}

func selectExec() {
	db := getInitDb()
	var user User
	//获取第一条记录， 主键升序
	db.Model(&User{}).First(&user, 1)
	fmt.Println(user)
	//多条查询
	var users []User
	db.Model(&User{}).Find(&users)
	fmt.Println(users)
}

func updateExec() {
	db := getInitDb()
	var user User
	//db.Find(&user, "id = ?", 3)
	//条件查询
	db.Where("id = ?", 3).Find(&user)
	user.Name = "liss"
	db.Save(&user)

}

// 关联创建
func linkCreate() {
	db := getInitDb()

	//db.AutoMigrate(&User{}, &CreditCard{})

	//一对一关联创建
	db.Create(&User{
		Name: "李四",
	},
	)

}

// 信用卡
type CreditCard struct {
	gorm.Model
	Number string
	UserID string
}

// 信用卡表自定义表名
func (CreditCard) TableName() string {
	return "t_credit_card"
}

func (User) TableName() string {
	return "t_user"
}

type User struct {
	gorm.Model
	CreditCard CreditCard
	Name       string
}

// 批量更新学生信息表
func updStudent() {
	db := getInitDb()
	db.Session(&gorm.Session{CreateBatchSize: CreateBatchSize})

	stu := db.First(&Student{}, "id =?", 1)

	fmt.Println(stu)

}

// 学生结构体
type Student struct {
	gorm.Model
	StudentName string `gorm:"column: stu_name"`
	addr        string
}

type Person struct {
	ID         uint `gorm:"primaryKey unique"`
	CreateTime time.Time
	Name       string
	Address    string
}

// 自定义表明
func (Person) TableName() string {
	return "t_person"
}

func (Student) TableName() string {
	return "t_student"
}

// 初始化person
func initDBPerson() {
	db := getInitDb()

	//定义数据结构
	p := Person{
		CreateTime: time.Now(),
		Name:       "王五",
		Address:    "浙江宁波",
	}

	db.AutoMigrate(&Person{})

	db.Create(&p)

}

func getInitDb() *gorm.DB {
	db, err := gorm.Open(mysql.Open(DSN), &gorm.Config{})
	if err != nil {
		fmt.Println(err)
		recover()
	}
	return db
}

// 初始化数据源
func initDBStudent() {

	db := getInitDb()

	db.AutoMigrate(&Student{})

	stu := Student{
		StudentName: "zhangsan",
		addr:        "测试地址",
	}
	if tx := db.Create(&stu); tx.Error != nil {
		fmt.Printf("新增报错 %s \n", tx.Error.Error())
		tx.Rollback()
		return

	}

}
